package com.haver.controller;


import com.alibaba.fastjson.JSONObject;

import com.haver.base.BaseController;
import com.haver.entity.SingleEntity;
import com.haver.service.SingleService;
import com.haver.service.impl.SingleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.BufferedReader;

import java.io.IOException;
import java.util.List;



@WebServlet(name = "SingleController",urlPatterns="/haver")
public class SingleControllerPost extends BaseController {

    private SingleService singleService=new SingleServiceImpl();


    /**
     * post
     * @param servletResponse
     * @return
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

        BufferedReader reader = servletRequest.getReader();
        String result = reader.readLine();
        JSONObject jO=JSONObject.parseObject(result);
        String method = jO.getString("method");
        String name = jO.getString("name");
        Integer id = jO.getInteger("id");

        if("addRole".equals(method)){
            addRole(servletResponse, jO);

        }else if ("removeRole".equals(method)){

            remove(id);

        }else if("changeRole".equals(method)){
            update(name,id, servletResponse);

        }else if ("checkAll".equals(method)){
            checkAll(servletRequest,servletResponse);
        }
    }

    private void addRole(ServletResponse servletResponse, JSONObject jO) {
        String name= jO.getString("name");

        boolean check=name.equals("")?true:false;
        singleService.addRole(name);
        printData(check,null,200, servletResponse);
    }

    private void update(String name,Integer id, ServletResponse servletResponse) throws IOException {
        singleService.updateById(id,name);
        boolean check=name.equals("")?true:false;
        printData(check,null,200, servletResponse);

    }

    private void remove(Integer id) {


        singleService.removeById(id);


    }


    /**
     * get
     * @param servletResponse
     * @return
     */
    private List<SingleEntity> checkAll(ServletRequest servletRequest,ServletResponse servletResponse) {
        List<SingleEntity> singleEntities = singleService.checkAll();
        boolean check=( singleEntities== null || singleEntities.size()==0)?false:true;
        printData(check,singleEntities,404, servletResponse);
        return singleEntities;
    }

}
